package com.lemon.smartsafetynew.ui.fragment.user.register;

import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafetynew.entity.event.user.PageEvent;
import com.lemon.smartsafetynew.net.services.AccountServices;
import com.lemon.smartsafetynew.util.common.AppSharePreferenceUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.SafeCloudConstants;
import com.thefinestartist.finestwebview.FinestWebView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Andrew on 2017/7/18.
 */

public class UserRegisterStepOneFragment extends BaseFragment {


    @Bind(R.id.telephone_edit)
    EditText telephoneEdit;
    @Bind(R.id.error_info_tv)
    TextView errorInfoTv;
    @Bind(R.id.agreement_checked_imageView)
    ImageView agreementCheckedImageView;
    @Bind(R.id.agreement_tv)
    TextView agreementTv;


    private MaterialDialog materialDialog;

    @Override
    protected void getBaseArguments() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_user_register_step_one;
    }

    @Override
    protected void initViews() {

        // 用户协议
        String agreement = getString(R.string.user_agreement);
        SpannableString agreementSpannable = new SpannableString(agreement);

        ClickableSpan clickableSpan = new ClickableSpan() {

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(ds.linkColor);
                ds.setUnderlineText(false); //去掉下划线
            }

            @Override
            public void onClick(View widget) {

                new FinestWebView.Builder(getActivity()).theme(R.style.FinestWebViewTheme)
                        .showUrl(false)
                        .statusBarColorRes(R.color.colorPrimaryDark)
                        .toolbarColorRes(R.color.colorPrimary)
                        .titleColorRes(R.color.white)
                        .iconDefaultColorRes(R.color.finestWhite)
                        .progressBarColorRes(R.color.finestWhite)
                        .showSwipeRefreshLayout(true)
                        .swipeRefreshColorRes(R.color.colorPrimaryDark)
                        .menuSelector(R.drawable.selector_light_theme)
                        .menuTextGravity(Gravity.CENTER)
                        .menuTextPaddingRightRes(R.dimen.defaultMenuTextPaddingLeft)
                        .dividerHeight(0)
                        .gradientDivider(false)
                        .showMenuShareVia(false)
                        .stringResCopiedToClipboard(R.string.web_view_copied)
                        .stringResCopyLink(R.string.web_view_copy)
                        .stringResOpenWith(R.string.web_view_open)
                        .show(Constants.REGISTER_PROTOCOL_URL);

            }
        };

        agreementSpannable.setSpan(clickableSpan, 0, agreement.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        agreementTv.setText(getString(R.string.agree));
        agreementTv.append("《");
        agreementTv.append(agreementSpannable);
        agreementTv.append("》");
        agreementTv.setMovementMethod(LinkMovementMethod.getInstance());

        // 错误信息提示
        errorInfoTv.setText("");
        telephoneEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                errorInfoTv.setText("");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        // 使用手册默认同意
        agreementCheckedImageView.setSelected(true);

    }

    @OnClick({R.id.next_btn, R.id.agreement_checked_imageView})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.next_btn:

                String telephoneNum = telephoneEdit.getText().toString().trim();

                if (checkTelephoneNum(telephoneNum) && matcherTelephoneNum(telephoneNum)) {

                    if (checkAgreement()) {
                        // ==== 验证手机的合法性 API  成功后并保存手机号 ====
                        AccountServices.init().registerCheckTelephoneNum(telephoneNum);

                    } else {
                        errorInfoTv.setText(getString(R.string.not_selected_agreement_error));
                    }
                } else {
                    errorInfoTv.setText(getString(R.string.telephone_number_error));
                }

                break;

            case R.id.agreement_checked_imageView:
                agreementCheckedImageView.setSelected(!agreementCheckedImageView.isSelected());
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThread(HttpCallbackEvent<String> event) {
        if (KeyConstants.URL_REGISTER_TELEPHONE_NUM_CHECK.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                showDialog();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                cancelDialog();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    AppSharePreferenceUtil.getInstance().putString(SafeCloudConstants.USER_TELEPHONE_NUMBER, event.getObj());
                    AppService.getBus().post(new PageEvent());
                } else {
                    errorInfoTv.setText(event.getMsg());
                }
            }
        }
    }


    private boolean checkTelephoneNum(String telNum) {
        return !(null == telNum || "".equals(telNum));
    }

    private boolean matcherTelephoneNum(String telNum) {

        String pattern = "^\\d{11}$";
        Pattern mPattern = Pattern.compile(pattern);
        Matcher mMatcher = mPattern.matcher(telNum);

        return mMatcher.matches();
    }

    private boolean checkAgreement() {
        return agreementCheckedImageView.isSelected();
    }


    private void showDialog() {
        materialDialog = new MaterialDialog.Builder(getActivity())
                .content(R.string.please_wait)
                .progress(true, 0)
                .cancelable(false)
                .show();
    }

    private void cancelDialog() {
        if(materialDialog != null && materialDialog.isShowing()) {
            materialDialog.dismiss();
            materialDialog = null;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        cancelDialog();
    }
}
